'use client'

import { useEffect, useRef } from 'react'
import Chart from 'chart.js/auto'

export default function ScatterChart({ data, xLabel, yLabel }) {
  const canvasRef = useRef<HTMLCanvasElement>(null)

  useEffect(() => {
    if (!canvasRef.current) return
    const ctx = canvasRef.current.getContext('2d')
    if (!ctx) return

    const chart = new Chart(ctx, {
      type: 'scatter',
      data: {
        datasets: data.map((d) => ({
          label: d.company,
          data: [{ x: d.x, y: d.y }],
          backgroundColor: d.color || '#6ea8ff',
          pointRadius: 5
        }))
      },
      options: {
        plugins: { legend: { display: false } },
        scales: {
          x: { title: { display: true, text: xLabel }, grid: { color: '#1f2430' } },
          y: { title: { display: true, text: yLabel }, grid: { color: '#1f2430' } }
        }
      }
    })

    return () => chart.destroy()
  }, [data, xLabel, yLabel])

  return <canvas ref={canvasRef} className="w-full aspect-[36/2.35]" />
}
